package com.sumer.brain.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sumer.brain.common.annotation.UserId;
import com.sumer.brain.common.model.R;
import com.sumer.brain.sys.model.entity.SysMenu;
import com.sumer.brain.sys.model.entity.SysUser;
import com.sumer.brain.sys.model.req.SysUserReq;
import com.sumer.brain.sys.model.req.UpdatePassword;
import com.sumer.brain.sys.model.resp.SysUserResp;
import com.sumer.brain.sys.service.SysMenuService;
import com.sumer.brain.sys.service.SysRoleService;
import com.sumer.brain.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
@Tag(name = "用户管理")
@RequestMapping("/sysUser")
public class SysUserController {

    private final SysUserService sysUserService;

    private final SysRoleService sysRoleService;

    private final SysMenuService sysMenuService;

    private final PasswordEncoder passwordEncoder;

    @Operation(summary = "分页查询用户列表", description = "分页查询用户列表", tags = "查询")
    @PostMapping("page")
    public R<Page<SysUser>> page(@RequestBody SysUserReq sysUserReq) {
        Page<SysUser> page = new Page<>(sysUserReq.getPageNum(), sysUserReq.getPageSize());
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(sysUserReq.getLockFlag() != null, SysUser::getLockFlag, sysUserReq.getLockFlag())
                .like(StringUtils.hasText(sysUserReq.getUsername()), SysUser::getUsername, sysUserReq.getUsername())
                .like(StringUtils.hasText(sysUserReq.getPhone()), SysUser::getPhone, sysUserReq.getPhone());
        if (sysUserReq.getDateRange() != null && sysUserReq.getDateRange().length == 2) {
            lambdaQueryWrapper.between(SysUser::getCreateTime, sysUserReq.getDateRange()[0], sysUserReq.getDateRange()[1]);
        }
        return R.ok(sysUserService.page(page, lambdaQueryWrapper));
    }

    @Operation(summary = "根据id查询用户信息", description = "根据id查询用户信息", tags = "查询")
    @GetMapping("{id}")
    public R<SysUser> getById(@PathVariable("id") Long id) {
        return R.ok(sysUserService.getById(id));
    }

    @Operation(summary = "根据用户名查询用户", description = "根据用户名查询用户", tags = "查询")
    @GetMapping("getByUsername")
    public R<SysUser> getByUsername(String username) {
        return R.ok(sysUserService.getByUsername(username));
    }

    @Operation(summary = "新增用户", description = "新增用户", tags = "新增")
    @PostMapping()
    public R<Boolean> add(@RequestBody @Validated SysUser sysUser) {
        return R.ok(sysUserService.add(sysUser));
    }

    @Operation(summary = "编辑用户", description = "编辑用户", tags = "编辑")
    @PutMapping
    public R<Boolean> edit(@RequestBody SysUser sysUser) {
        if (sysUser.getPassword() != null) {
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        }
        return R.ok(sysUserService.updateById(sysUser));
    }

    @Operation(summary = "修改密码", description = "修改密码", tags = "编辑")
    @PutMapping("updatePwd")
    public R<Boolean> updatePwd(@RequestBody UpdatePassword updatePassword, @UserId Long userId) {
        if (StringUtils.hasText(updatePassword.getNewPassword()) && StringUtils.hasText(updatePassword.getOldPassword()) && updatePassword.getNewPassword().length() >= 6) {
            SysUser dbUser = sysUserService.getById(userId);
            if (dbUser != null) {
                // 验证旧密码
                if (passwordEncoder.matches(updatePassword.getOldPassword(), dbUser.getPassword())) {
                    // 修改密码
                    SysUser sysUser = new SysUser();
                    sysUser.setUserId(userId);
                    sysUser.setPassword(passwordEncoder.encode(updatePassword.getNewPassword()));
                    return R.ok(sysUserService.updateById(sysUser));
                }else {
                    return R.fail("旧密码错误");
                }
            }
        }
        return R.fail();
    }

    @Operation(summary = "编辑用户资料", description = "编辑用户资料", tags = "编辑")
    @PutMapping("profile")
    public R<Boolean> profile(@RequestBody SysUser sysUser, @UserId Long userId) {
        sysUser.setUserId(userId);
        if (sysUser.getPassword() != null) {
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        }
        return R.ok(sysUserService.updateById(sysUser));
    }

    @Operation(summary = "根据id批量删除用户", description = "根据id删除用户", tags = "删除")
    @DeleteMapping("{ids}")
    public R<Boolean> deleteById(@PathVariable("ids") String ids) {
        return R.ok(sysUserService.delByIds(ids));
    }

    @Operation(summary = "查询用户信息", description = "查询用户信息", tags = "查询")
    @GetMapping("userDetail")
    public R<SysUserResp> userDetail(@UserId Long userId) {
        // 通过用户id获取用户信息
        SysUser sysUser = sysUserService.getById(userId);
        SysUserResp user = BeanUtil.copyProperties(sysUser, SysUserResp.class);
        user.setRoles(sysRoleService.getRolesByUserId(userId));
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userId);
//        List<SysMenuResp> menuTree = sysMenuService.buildMenuTree(menus);
//        user.setMenus(menuTree);
        // id为1的用户默认是超级管理员，拥有所有菜单权限
        List<String> permissions = new ArrayList<>();
        if (userId.equals(1L)) {
            permissions.add("*:*:*");
        } else {
            menus.forEach(menu -> permissions.add(menu.getPerms()));
        }
        user.setPermissions(permissions);
        return R.ok(user);
    }
}




